<template>
  <div class="standard-management">
    <div class="header-actions">
      <h1>标准问题管理</h1>
      <div>
        <button 
          v-if="selectedCount > 0 && !isFromEvalTaskGenerator"
          @click="openEvaluationCreator"
          class="create-evaluation-btn"
        >
          创建评测任务 ({{ selectedCount }})
        </button>
        <button 
          v-if="isFromEvalTaskGenerator"
          @click="returnToEvalTaskGenerator"
          class="return-btn"
        >
          返回评测任务生成器 ({{ selectedCount }})
        </button>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-area">
      <div class="filter-tabs">
        <button 
          :class="{ active: activeTab === 'active' }"
          @click="switchTab('active')"
        >
          活跃标准问题
          <span v-if="activeTab === 'active'" class="badge">{{ pagination.total }}</span>
        </button>
        <button 
          :class="{ active: activeTab === 'inactive' }"
          @click="switchTab('inactive')"
        >
          不活跃标准问题
          <span v-if="activeTab === 'inactive'" class="badge">{{ pagination.total }}</span>
        </button>
        <button 
          :class="{ active: activeTab === 'no-answer' }"
          @click="switchTab('no-answer')"
        >
          无答案标准问题
          <span v-if="activeTab === 'no-answer'" class="badge">{{ pagination.total }}</span>
        </button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-inputs">
        <input v-model="searchId" placeholder="输入问题ID" />
        <button @click="handleIdSearch()">精确搜索</button>
      </div>
      
      <div class="search-inputs">
        Category:
        <select v-model="searchRequest.category" class="category-select">
          <option value="">所有分类</option>
          <option v-for="category in allCategories" :key="category" :value="category">{{ category }}</option>
        </select>
        <!-- <button @click="handleSearch(1)">按分类筛选</button> -->
        <input v-model="searchRequest.keyword" placeholder="输入问题内容" />
        <div class="search-inputs">
        <button @click="handleSearch(1)">搜索</button>
      </div>
      </div>
      <!-- 标签选择区域 -->
      <div class="tag-selection">
        <div class="tag-toggle" @click="toggleTagPanel">
          <span>标签筛选</span>
          <span class="toggle-icon">{{ showTagPanel ? '▲' : '▼' }}</span>
        </div>
        <div class="tag-panel" v-show="showTagPanel">
          <div class="tag-container">
            <div 
              v-for="tag in allTags" 
              :key="tag"
              class="tag-item"
              :class="{ selected: selectedTags.includes(tag) }"
              @click="toggleTagSelection(tag)"
            >
              {{ tag }}
            </div>
          </div>
          <div class="selected-tags" v-if="selectedTags.length > 0">
            <span>已选标签：</span>
            <span 
              v-for="tag in selectedTags" 
              :key="'selected-'+tag"
              class="selected-tag"
            >
              {{ tag }}
              <span class="remove-tag" @click.stop="removeTag(tag)">×</span>
            </span>
            <button 
              @click="clearTagSelection"
              class="clear-tag-btn"
            >
              清除全部
            </button>
          </div>
        </div>
      </div>      
    </div>

    <!-- 结果表格 -->
    <div class="results-table">
      <table v-if="searchResults.length > 0">
        <thead>
          <tr>
            <th>ID</th>
            <th>问题内容</th>
            <th>原始问题ID</th>
            <th>状态</th>
            <th>分类</th>
          </tr>
        </thead>
        <tbody>
          <tr 
            v-for="item in searchResults" 
            :key="item.id"
            @click="goToStandardDetail(item)"
            class="clickable-row"
          >
            <td>
              <input 
                v-if="llmStore.showLLMDialog || evaluationStore.showEvaluationCreator"
                type="checkbox" 
                :checked="llmStore.showLLMDialog 
                  ? llmStore.selectedQuestions.includes(item.id)
                  : evaluationStore.selectedQuestionIds.includes(item.id)"
                @click.stop="llmStore.showLLMDialog
                  ? (llmStore.selectedQuestions.includes(item.id) 
                    ? llmStore.selectedQuestions = llmStore.selectedQuestions.filter(q => q !== item.id)
                    : llmStore.selectedQuestions.push(item.id))
                  : (evaluationStore.selectedQuestionIds.includes(item.id)
                    ? evaluationStore.selectedQuestionIds = evaluationStore.selectedQuestionIds.filter(q => q !== item.id)
                    : evaluationStore.selectedQuestionIds.push(item.id))"
              >
              {{ item.id }}
            </td>
            <td>{{ item.question }}</td>
            <td>{{ item.originalQuestion.id }}</td>
            <td>{{ item.active ? '活跃' : '不活跃' }}</td>
            <td>{{ item.category || '-' }}</td>
          </tr>
        </tbody>
      </table>
      <div v-else class="no-results">
        <p>暂无结果</p>
      </div>
    </div>

    <!-- 百度风格分页组件 -->
    <div class="baidu-pagination" v-if="searchResults.length > 0">
      <div class="pagination-container">
        <span 
          class="page-btn prev" 
          :class="{ disabled: pagination.currentPage <= 1 }"
          @click="pagination.currentPage > 1 ? handleSearch(pagination.currentPage - 1) : null"
        >
          <span class="arrow">←</span> 上一页
        </span>
        
        <span
          v-for="page in getDisplayPages()"
          :key="page"
          class="page-number"
          :class="{ 
            active: pagination.currentPage === page,
            ellipsis: page === '...'
          }"
          @click="page !== '...' && handleSearch(Number(page))"
        >
          {{ page }}
        </span>
        
        <span 
          class="page-btn next" 
          :class="{ disabled: pagination.currentPage * pagination.pageSize >= pagination.total }"
          @click="pagination.currentPage * pagination.pageSize < pagination.total ? handleSearch(pagination.currentPage + 1) : null"
        >
          下一页 <span class="arrow">→</span>
        </span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useVersionStore } from '@/stores/versionStore'
import { useLLMStore } from '@/stores/llmStore'
import { useEvaluationStore } from '@/stores/evaluation'
import EvalTaskGenerator from '@/components/EvalTaskGenerator.vue'
import { 
  getStandardQuestionById,
  searchStandardQuestions,
  getAllTags,
  getAllCategories,
  type StandardQuestion,
  type QuestionSearchRequest
} from '@/api/question'

export default defineComponent({
  name: 'StandardManagement',
  components: {
    EvalTaskGenerator
  },
  setup() {
    const evaluationStore = useEvaluationStore()
    const router = useRouter()
    const route = useRoute()
    const versionStore = useVersionStore()
    const activeTab = ref('active') // 默认显示活跃标准问题
    const searchId = ref('') // 精确搜索ID
    const isFromEvalTaskGenerator = ref(false)
    
    const searchResults = ref<StandardQuestion[]>([])
    const llmStore = useLLMStore()
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    const allTags = ref<string[]>([])
    const allCategories = ref<string[]>([])
    const selectedTags = ref<string[]>([])
    const showTagPanel = ref(false)

    // 切换筛选标签
    const switchTab = (tab: string) => {
      activeTab.value = tab
      // 更新搜索条件
      searchRequest.value.isActive = tab === 'active' ? true : 
                                   tab === 'inactive' ? false : undefined
      searchRequest.value.hasStandardAnswer = tab === 'no-answer' ? false : undefined
      // 重置其他搜索条件
      searchRequest.value.keyword = undefined
      searchRequest.value.tags = undefined
      selectedTags.value = []
      searchId.value = ''
      // 触发搜索
      handleSearch(1)
    }

    // 维护搜索请求对象
    const searchRequest = ref<QuestionSearchRequest>({
      versionId: versionStore.currentVersion?.ver_code || '',
      isActive: undefined,
      hasStandardAnswer: undefined,
      tags: undefined,
      keyword: undefined,
      category: undefined
    })

    // 处理筛选搜索
    const handleSearch = async (page = 1) => {
      try {
        pagination.value.currentPage = page
        
        // 确保版本ID是最新的
        searchRequest.value.versionId = versionStore.currentVersion?.ver_code || ''
        
        const response = await searchStandardQuestions(
          searchRequest.value,
          page - 1,  // page参数从0开始
          pagination.value.pageSize
        )
        searchResults.value = response.content || []
        pagination.value.total = response.totalElements || 0
      } catch (error) {
        console.error('搜索失败:', error)
      }
    }

    // 处理精确ID搜索
    const handleIdSearch = async () => {
      if (!searchId.value) return
      
      try {
        const id = parseInt(searchId.value)
        if (isNaN(id)) return
        activeTab.value = ''
        const result = await getStandardQuestionById(id, versionStore.currentVersion?.ver_code || 'unknown')
        searchResults.value = [result]
        pagination.value = {
          currentPage: 1,
          pageSize: 10,
          total: 1
        }
      } catch (error) {
        console.error('精确搜索失败:', error)
        searchResults.value = []
      }
    }

    // 切换标签面板显示状态
    const toggleTagPanel = () => {
      showTagPanel.value = !showTagPanel.value
    }

    // 切换标签选择状态
    const toggleTagSelection = (tag: string) => {
      const index = selectedTags.value.indexOf(tag)
      if (index === -1) {
        selectedTags.value.push(tag)
      } else {
        selectedTags.value.splice(index, 1)
      }
      // 只更新搜索条件，不触发搜索
      searchRequest.value.tags = selectedTags.value.length > 0 ? selectedTags.value : undefined
    }

    // 移除单个标签
    const removeTag = (tag: string) => {
      const index = selectedTags.value.indexOf(tag)
      if (index !== -1) {
        selectedTags.value.splice(index, 1)
        // 只更新搜索条件，不触发搜索
        searchRequest.value.tags = selectedTags.value.length > 0 ? selectedTags.value : undefined
      }
    }

    // 清除标签选择
    const clearTagSelection = () => {
      selectedTags.value = []
      searchRequest.value.tags = undefined
    }

    // 跳转到标准问题详情
    const goToStandardDetail = (question: StandardQuestion) => {
      router.push({
        name: 'standardDetail',
        params: {
          id: question.id.toString(),
          originalId: question.originalQuestion.id.toString(),
          version: versionStore.currentVersion?.ver_code || question.originalQuestion.version || '1.0'
        }
      })
    }

    // 获取显示的页码数组(带省略号)
    const getDisplayPages = () => {
      const totalPages = Math.ceil(pagination.value.total / pagination.value.pageSize)
      const current = pagination.value.currentPage
      const range = 2 // 当前页前后显示的页码数
      const pages = []
      
      if (totalPages <= 7) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i)
        }
        return pages
      }
      
      // 添加前几页
      for (let i = 1; i <= 3; i++) {
        pages.push(i)
      }
      
      // 添加省略号或中间页码
      if (current > range + 3) {
        pages.push('...')
      }
      
      // 添加当前页附近的页码
      const start = Math.max(4, current - range)
      const end = Math.min(totalPages - 1, current + range)
      for (let i = start; i <= end; i++) {
        if (!pages.includes(i)) pages.push(i)
      }
      
      // 添加省略号或最后几页
      if (current < totalPages - range - 2) {
        pages.push('...')
      }
      
      // 添加最后几页
      for (let i = totalPages - 2; i <= totalPages; i++) {
        if (!pages.includes(i)) pages.push(i)
      }
      
      return pages
    }

    // 初始化加载数据
    onMounted(async () => {
      // 检查是否从EvalTaskGenerator跳转过来
      if (route.query.returnTo === 'EvalTaskGenerator') {
        isFromEvalTaskGenerator.value = true
        if (route.query.selectedQuestions) {
          const selected = route.query.selectedQuestions.toString().split(',').map(Number)
          evaluationStore.selectedQuestionIds = [...selected]
        }
      }
      // 加载所有标签和分类
      try {
        allTags.value = await getAllTags()
        allCategories.value = await getAllCategories(versionStore.currentVersion?.ver_code || '')
      } catch (error) {
        console.error('加载标签或分类失败:', error)
      }
      // 根据默认activeTab状态设置搜索条件
      searchRequest.value.isActive = true
      searchRequest.value.hasStandardAnswer = undefined
      handleSearch(1)
    })
    
    // 返回EvalTaskGenerator并传递选中的问题
    const returnToEvalTaskGenerator = () => {
      router.push({
        name: 'EvalTaskGenerator',
        query: {
          selectedQuestions: evaluationStore.selectedQuestionIds.join(',')
        }
      })
    }

    // // 初始化时清空选择
    // onMounted(() => {
    //   llmStore.selectedQuestions = []
    //   llmStore.selectedModels = []
    // })

    const selectedCount = computed(() => evaluationStore.selectedQuestionIds.length)

    const openEvaluationCreator = () => {
      evaluationStore.toggleEvaluationCreator(true)
    }

    // 导出当前搜索结果
    const exportResults = () => {
      return {
        searchResults: searchResults.value,
        pagination: pagination.value,
        activeTab: activeTab.value,
        selectedTags: selectedTags.value
      }
    }

    return {
      activeTab,
      searchId,
      searchResults,
      handleSearch,
      handleIdSearch,
      goToStandardDetail,
      pagination,
      getDisplayPages,
      switchTab,
      llmStore,
      evaluationStore,
      selectedCount,
      openEvaluationCreator,
      isFromEvalTaskGenerator,
      returnToEvalTaskGenerator,
      clearTagSelection,
      allTags,
      allCategories,
      selectedTags,
      toggleTagSelection,
      removeTag,
      exportResults,
      showTagPanel,
      toggleTagPanel,
      searchRequest
    }
  }
})
</script>

<style scoped>
.standard-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.create-evaluation-btn {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  margin-right: 10px;
}

.create-evaluation-btn:hover {
  background-color: #3e8e41;
}

.return-btn {
  padding: 8px 16px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.return-btn:hover {
  background-color: #0b7dda;
}

/* 模型选择区域 */
.model-selection {
  margin: 20px 0;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.model-selection h3 {
  margin-top: 0;
  margin-bottom: 12px;
  color: #2c3e50;
}

.model-options {
  display: flex;
  gap: 16px;
}

.model-options label {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

/* 表格中的复选框 */
.results-table input[type="checkbox"] {
  margin-right: 8px;
  cursor: pointer;
}

/* 筛选标签样式 */
.filter-area {
  margin: 20px 0;
}

.filter-tabs {
  display: flex;
  gap: 10px;
}

.filter-tabs button {
  position: relative;
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.filter-tabs button.active {
  background-color: #2c3e50;
  color: white;
}

.filter-tabs .badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #42b983;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.filter-status {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

/* 搜索区域样式 */
.search-area {
  margin: 20px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-inputs {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.search-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-group input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 200px;
}

.search-group input[type="number"] {
  width: 120px;
}

.tag-selection {
  display: flex;
  gap: 10px;
  align-items: center;
}

.tag-input {
  position: relative;
  display: flex;
  align-items: center;
}

.tag-toggle {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  margin-bottom: 8px;
}

.tag-toggle:hover {
  background-color: #e8e8e8;
}

.toggle-icon {
  margin-left: 8px;
  font-size: 12px;
}

.tag-panel {
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 10px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.tag-item {
  padding: 6px 12px;
  background-color: #f0f0f0;
  border-radius: 16px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.tag-item:hover {
  background-color: #e0e0e0;
}

.tag-item.selected {
  background-color: #2c3e50;
  color: white;
}

.selected-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  font-size: 14px;
}

.selected-tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
}

.remove-tag {
  margin-left: 4px;
  cursor: pointer;
  color: #1890ff;
  font-weight: bold;
}

.remove-tag:hover {
  color: #096dd9;
}

.clear-tag-btn {
  margin-left: 10px;
  padding: 4px 8px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: #666;
  cursor: pointer;
  font-size: 14px;
}

.clear-tag-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.search-inputs input,
.search-inputs select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
}

.category-select {
  min-width: 150px;
}

.search-inputs button,
.search-btn {
  padding: 8px 16px;
  background-color: #2c3e50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.search-btn {
  margin-top: 10px;
  width: 100%;
}

.search-inputs button:hover {
  background-color: #1a252f;
}

/* 结果表格样式 */
.results-table {
  margin: 20px 0;
  overflow-x: auto;
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.no-results {
  color: #666;
  font-size: 16px;
  text-align: center;
  padding: 20px;
}

.results-table table {
  width: 100%;
  border-collapse: collapse;
}

.results-table th,
.results-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.results-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.results-table tr:hover {
  background-color: #f9f9f9;
}

.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #e6f7ff !important;
}

/* 百度风格分页样式 */
.baidu-pagination {
  margin: 30px 0;
  text-align: center;
}

.pagination-container {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  display: inline-block;
  padding: 0 12px;
  height: 34px;
  line-height: 34px;
  color: #333;
  cursor: pointer;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  background: #fff;
  font-size: 14px;
}

.page-btn:hover:not(.disabled) {
  color: #315efb;
  border-color: #315efb;
}

.page-btn.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.page-btn .arrow {
  font-weight: bold;
}

.page-number {
  display: inline-block;
  min-width: 34px;
  height: 34px;
  line-height: 34px;
  color: #333;
  cursor: pointer;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  background: #fff;
  text-align: center;
  font-size: 14px;
}

.page-number:hover:not(.active):not(.ellipsis) {
  color: #315efb;
  border-color: #315efb;
}

.page-number.active {
  color: #fff;
  background-color: #315efb;
  border-color: #315efb;
  cursor: default;
}

.page-number.ellipsis {
  border: none;
  background: transparent;
  cursor: default;
}
</style>
